package com.bajiao.app.controller.callback;

import cn.hutool.core.util.StrUtil;
import com.bajiao.common.constant.CommonConstant;
import com.bajiao.common.constant._Whole;
import com.bajiao.common.exception.DataHandleException;
import com.bajiao.common.util.DateUtils;
import com.bajiao.entity.account.Account;
import com.bajiao.entity.order.Order;
import com.bajiao.entity.order.RefundOrder;
import com.bajiao.entity.pay.PayNotifyData;
import com.bajiao.service.account.AccountService;
import com.bajiao.service.order.OrderService;
import com.bajiao.service.order.RefundOrderService;
import com.bajiao.service.recharge.RechargeService;
import com.bajiao.third.utils.WxPayUtils;
import com.ijpay.core.kit.WxPayKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags = "外部回调入口")
@RestController
@RequestMapping("/call")
public class CallbackController {

    @Resource
    private WxPayUtils wxPayUtils;
    @Resource
    private RechargeService rechargeService;
    @Resource
    private OrderService orderService;
    @Resource
    private RefundOrderService refundOrderService;

    @ApiModelProperty("微信充值支付回调")
    @RequestMapping("/wx/recharge")
    public String wxRecharge(HttpServletRequest request) {
        Map<String, String> result = new HashMap<String, String>(2);
        try {
            Map<String, String> map = wxPayUtils.payNotify(request);
            if (!WxPayKit.codeIsOk(map.get("result_code"))) {
                result.put("return_code", "SUCCESS");
                result.put("return_msg", "OK");
                return WxPayKit.toXml(result);
            }
            String attach = "";
            if (StrUtil.isNotBlank(attach)) {
                attach = URLDecoder.decode(map.get("attach"));
            }
            PayNotifyData payNotifyData = PayNotifyData.PayNotifyDataBuilder.aPayNotifyData()
                    .type(CommonConstant.PAYMENT_TYPE_WX)
                    .params(attach)
                    .tradeNo(map.get("transaction_id"))
                    .outTradeNo(map.get("out_trade_no"))
                    .totalMoney(map.get("total_fee"))
                    .payTime(DateUtils.stringToDate(map.get("time_end"), "yyyyMMddHHmmss"))
                    .build();
            //调用更改订单状态的方法
            rechargeService.completePayment(payNotifyData);
        } catch (DataHandleException d) {
            if (d.getCode() == 0) {
                result.put("return_code", "FAIL");
                result.put("return_msg", d.getMessage());
                return WxPayKit.toXml(result);
            }
        }
        result.put("return_code", "SUCCESS");
        result.put("return_msg", "OK");
        return WxPayKit.toXml(result);
    }

    @Resource
    private AccountService accountService;

    @ApiModelProperty("微信订单支付回调")
    @RequestMapping("/wx/order")
    public String wxOrder(HttpServletRequest request) {
        Map<String, String> result = new HashMap<String, String>(2);
        try {
            Map<String, String> map = wxPayUtils.payNotify(request);
            if (!WxPayKit.codeIsOk(map.get("result_code"))) {
                result.put("return_code", "SUCCESS");
                result.put("return_msg", "OK");
                return WxPayKit.toXml(result);
            }
            Order order = orderService.getByPayNo(map.get("out_trade_no"));
            order.setPayPrice(new BigDecimal(map.get("total_fee")).divide(new BigDecimal("100"), _Whole.TWO, BigDecimal.ROUND_DOWN));
            order.setOutTradeNo(map.get("transaction_id"));
            //调用更改订单状态的方法
            orderService.complete(order);

            // 同步用户账户信息
            Account account = accountService.queryByUserId(order.getUserId());
            account.setMoney(account.getMoney().subtract(order.getDiscountAmount()));
            accountService.updateById(account);
        } catch (DataHandleException d) {
            if (d.getCode() == 0) {
                result.put("return_code", "FAIL");
                result.put("return_msg", d.getMessage());
                return WxPayKit.toXml(result);
            }
        }
        result.put("return_code", "SUCCESS");
        result.put("return_msg", "OK");
        return WxPayKit.toXml(result);
    }

    @ApiModelProperty("微信订单退款通知")
    @RequestMapping(value = "/wx/order/refund", method = {RequestMethod.POST, RequestMethod.GET})
    public String refundNotify(HttpServletRequest request) {
        log.info("##############收到退款通知#################");
        Map<String, String> result = new HashMap<String, String>(2);
        try {
            refundOrderService.refundNotify(request);
        } catch (DataHandleException d) {
            result.put("return_code", "FAIL");
            result.put("return_msg", d.getMessage());
            return WxPayKit.toXml(result);
        }
        result.put("return_code", "SUCCESS");
        result.put("return_msg", "OK");
        return WxPayKit.toXml(result);
    }
}
